package dispatcher.group.gui.listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import dispatcher.gui.GroupDispatcherView;

import state.group.events.BaseEvent;
import state.group.events.DeregistrationEvent;
import state.group.events.EventCollection;
import state.group.events.RegistrationEvent;

/**
 * his class waits for an ElevatorUpdateEvent to appear then proceeds to either
 * remove an elevator from the GUI if it receives a deregistration message
 * or create another elevator if it receives a registration message
 * @author Caleb
 *
 */
public class ElevatorUpdateListener implements ActionListener {

	/**
	 * This method will create new elevators or remove elevators in the GUI
	 */
	@Override
	public void actionPerformed(ActionEvent arg0) {
		if (arg0 instanceof ElevatorUpdateEvent){
			EventCollection collection = ((ElevatorUpdateEvent)arg0).getCollection();
			
			// Loops through all the events
			for(BaseEvent b : collection){
				switch(b.getEventType()){
				
					case RegistrationEvent:	
						
						RegistrationEvent rEvent = (RegistrationEvent)b;
						
						System.out.println("Elevator Registered : " + rEvent.getElevatorId());
						// If registration event has occurred, it will create a new elevator
						GroupDispatcherView.getInstance().createElevator(rEvent.getElevatorId());
						
						break;
					case DeregistrationEvent:
						
						DeregistrationEvent dEvent = (DeregistrationEvent)b;
						
						System.out.println("Elevator Registered : " + dEvent.getElevatorId());
						// If deregistration event has occurred, it will remove a elevator
						GroupDispatcherView.getInstance().removeElevator(dEvent.getElevatorId());
						
						break;
						
					default:
						// Everything else will be ignored
						break;
				}
			}
			GroupDispatcherView.getInstance().refreshGUI();
		}
	}

}
